package com.example.stmall.manager.service.impl;

import com.example.stmall.manager.entity.Category;
import com.example.stmall.manager.mapper.CategoryMapper;
import com.example.stmall.manager.service.CategoryService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Service层实现类
 * 1.需要实现Service层的接口
 * 2.添加Service注解
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    //自动注入Mapper层的对象
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public int add(Category category) throws Exception {
        //1.验证参数
        if(category.getName() == null || category.getName().length() == 0){
            throw new Exception("分类名不能为空");
        }
        if(category.getRecom() == null){
            throw new Exception("推荐不能为空");
        }
        //2.逻辑处理
        //3.访问数据库
        return categoryMapper.insert(category);
    }

    @Override
    public int remove(Integer id) throws Exception {
        Category category = categoryMapper.selectById(id);
        if(category == null){
            throw new Exception("ID不存在！");
        }
        return categoryMapper.delete(id);
    }

    @Override
    public int edit(Category category) throws Exception {
        Category sCategory = categoryMapper.selectById(category.getId());
        if(sCategory == null){
            throw new Exception("ID不存在");
        }
        return categoryMapper.update(category);
    }

    @Override
    public Category getById(Integer id) {
        return categoryMapper.selectById(id);
    }

    @Override
    public List<Category> search(Category category) {
        return categoryMapper.select(category);
    }

    @Override
    public PageInfo searchByPage(Integer page, Integer limit, Category category) {

        //1.启动分页查询
        PageHelper.startPage(page,limit);

        //2.调用Mapper层
        List<Category> list = categoryMapper.select(category);

        //3.构造PageInfo对象
        PageInfo pageInfo = new PageInfo(list);

        return pageInfo;
    }
}
